package com.cgt.xiaotao.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgt.common.exception.BadRequestException;
import com.cgt.common.utils.UserContext;
import com.cgt.xiaotao.order.config.AlipayConfig;
import com.cgt.xiaotao.order.domain.po.Order;
import com.cgt.xiaotao.order.domain.po.Payment;
import com.cgt.xiaotao.order.mapper.OrderMapper;
import com.cgt.xiaotao.order.mapper.PaymentMapper;
import com.cgt.xiaotao.order.service.IPaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@RequiredArgsConstructor
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements IPaymentService {

    private final OrderMapper orderMapper;
    private final AlipayConfig alipayConfig;

    static final String NotifyUrl = "https://2ea457f4.r19.vip.cpolar.cn" + "/pay/callback";
    static final String ReturnUrl = "http://localhost:5173" + "/success";

    @Override
    public String aliPay(String orderNo) {
        // 1.获取用户id
        Long userId = UserContext.getUser();
        // 2.根据订单编号和用户id查询订单
        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getUserId, userId));
        if (order == null) {
            throw new BadRequestException("订单不存在");
        }
        // 3.根据订单详情查询支付记录
        Payment payment = this.lambdaQuery().eq(Payment::getOrderId, order.getId())
                .eq(Payment::getUserId, userId)
                .one();

        AlipayClient alipayClient = null;
        // 初始化SDK
        try {
            alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
        }catch (Exception e) {
            throw new BadRequestException("初始化SDK");
        }

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        // 设置商户订单号
        model.setOutTradeNo(orderNo);

        // 设置订单总金额
        model.setTotalAmount(payment.getTotalAmount().toString());

        // 设置订单标题
        model.setSubject(order.getName() + "的小淘购物车支付");

        // 设置商品描述
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置PC扫码支付的方式
        model.setQrPayMode("1");

        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(100L);

        try {
            // 设置回调参数 订单编号
            model.setPassbackParams(java.net.URLEncoder.encode("orderNo=" + orderNo, "UTF-8"));
        } catch (Exception e) {
            throw new BadRequestException("设置回调参数失败");
        }

        request.setBizModel(model);
        request.setNotifyUrl(NotifyUrl);
        // 不要在returnUrl中直接拼接参数
        request.setReturnUrl(ReturnUrl);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
        AlipayTradePagePayResponse response = null;
        try {
            // 使用GET请求方式获取URL
            response = alipayClient.pageExecute(request, "POST");
        }catch (Exception e) {
            throw new BadRequestException("alipayClient发送请求失败");
        }
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }

        return pageRedirectionData;
    }

    // 支付宝回调函数
    @Override
    public void callback(Map<String, String> params) {
        log.debug("支付宝回调:{}", params);
        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            Payment payment = this.lambdaQuery().eq(Payment::getOrderNo, params.get("out_trade_no"))
                    .one();
            payment.setPaymentMethod((byte) 1);
            payment.setStatus((byte) 1);
            payment.setTransactionId(params.get("trade_no"));
            try {
                // 解析时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date payTime = sdf.parse(params.get("gmt_payment"));
                payment.setPayTime(payTime);
            } catch (ParseException e) {
                log.error("日期解析失败: ", e);
                payment.setPayTime(new Date());
            }
            payment.setCallbackTime(new Date());
            orderMapper.update(new Order(), new LambdaUpdateWrapper<Order>().eq(Order::getId, payment.getOrderId()).set(Order::getStatus,(byte) 1));
            this.updateById(payment);
        }
    }
}
